import pageination from '../../components/pageination/pageination.vue'
export default {
  data() {
    return {
      //数据

      searchValue: "",
      userId: 0,
      thatUrl: this.urls.baseUrl,
      FileUpload: [],
      testAttachment: '', // 文本附件

      imageAttachment:'',
      FileUploadImg: [],

      videoAttachment: '',
      FileUploadVideo: [],

      studentObj: {},
      studentId: null,
      validate: {},
      student: [], // table
      total: 0, //总条数
      page: 1, //当前页
      size: 10,//每页显示条数
      ApplicationStatus: false,
      Application: false,
      curId: 0,
      uploadNum: 0,
      isModify:false,//true 修改  false新增
    }
  },
  components: {
    pageination
  },
  created() { //调用方法
    this.getStudent();
  },
  mounted() {
    jQuery.validator.addMethod("isMobile", function(value, element) {
      let length = value.length;
      let mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
      return this.optional(element) || (length == 11 && mobile.test(value));
    }, "请正确填写手机号码");
    //加载表单验证
    this.validate = $("#studentForm").validate({
      ignore: [],
      rules: {
        name: { // 名称
          required: true,
          maxlength: 10
        },
        identityCard: { // 名称
          required: true,
          maxlength: 18,
          minlength: 18,
          number: true
        },
        phone: { // 名称
          required: true,
          maxlength: 11,
          isMobile: true
        },
        industry: { // 名称
          required: true,
          maxlength: 10
        },
        reserved2: { // 名称
          required: true,
          maxlength: 50,
          email: true
        },

      },
      messages: {
        name: { // 名称
          required: '名称不能为空',
          maxlength: '最大长度为10'
        },
        identityCard: { // 名称
          required: '身份证不能为空',
          maxlength: '最大长度为18',
          minlength: '身份证最小长度为18',
          number: '只能输入数字'
        }
        ,  phone: { // 名称
          required: '联系方式不能为空',
          maxlength: '最大长度为11',
          isMobile: '请输入正确的联系方式'
        }
        ,  industry: { // 名称
          required: '职业不能为空',
          maxlength: '最大长度为10'
        }
        ,  reserved2: { // 名称
          required: '邮箱不能为空',
          maxlength: '最大长度为50',
          email: '请输入正确的邮箱'
        }

      },
      /*errorElement: "em",
      errorPlacement: function(error, element) {
        error.appendTo(element.parents(".error-box").children(".error-msg"));
      }*/
    });
  },
  methods: { //写函数方法
    //页码切换执行方法
    getStudent: function () {
      let that = this;
      let obj =  {"pageNum": that.page, "pageSize": that.size, "auditStatus": 1};
      let name = $('#searchName').val();
      let value = $('#searchValue').val();
      obj[name] = value;
      that.$post(
        that.urls.findAllStudent,
        obj
      )
        .then(function(res) {
          if(res.success) {
            that.student = res.pageInfo.list;
            that.page = res.pageInfo.pageNum;
            that.total = res.pageInfo.total;

          }
        })
    },

    pageFn: function(val, pid) {
      this.page = parseInt(val);
      this.getStudent();
      //此处调列表数据接口
    },
    /**返回子组件用户选择的一页显示条数**/
    obtainChild: function(data) {
      this.row = data;
    },
    //人工录入及修改模态框
    manually:function(id){
      $("#studentForm").validate().resetForm();
      $("input[type='reset']").trigger("click");

      this.studentId = 0;
      this.userId = 0;
      this.testAttachment = '';
      this.FileUpload = [];
      this.imageAttachment = '';
      this.FileUploadImg = [];
      this.videoAttachment = '';
      this.FileUploadVideo = [];
      let that = this;
      that.studentObj = {};
      that.ApplicationStatus = true;
      if(! id){
      	this.isModify=false;
        return;
      }
      this.isModify=true;
      that.studentId = id;
      that.$post(
        that.urls.getStudent,
        {"id": id}
      )
        .then(function(res) {
          if(res.success) {
            that.studentObj = res.data;
            that.userId = res.data.userId;
            $('#reserved').val(that.studentObj.reserved);

            that.testAttachment = res.data.testAttachment;
            that.imageAttachment = res.data.imageAttachment;
            that.videoAttachment = res.data.videoAttachment;

            let enclosureList = [];  // 查看tex

            let enclosures = res.data.testAttachment.split(";");
            if(enclosures.length > 0 && res.data.testAttachment) {
              enclosures.forEach(function (e) {
                enclosureList.push({
                  "name": that.getFileName(that.getFileName(e)),
                  "url":  e
                });
              })
            }
            that.FileUpload = enclosureList;

            let imgArr = [];
            // 查看img
            let enclosuresImg = res.data.imageAttachment.split(";");
            if(enclosuresImg.length > 0 && res.data.imageAttachment) {
              enclosuresImg.forEach(function (e) {
                imgArr.push({
                  "name": that.getFileName(that.getFileName(e)),
                  "url":   e
                });
              })
            }
            that.FileUploadImg = imgArr;

            let video = [];  // 查看video
            let enclosuresVideo = res.data.videoAttachment.split(";");
            if(enclosuresVideo.length > 0 && res.data.videoAttachment) {
              enclosuresVideo.forEach(function (e) {
                video.push({
                  "name": that.getFileName(that.getFileName(e)),
                  "url":   e
                });
              })
            }
            that.FileUploadVideo = video;

          }
        })

    },
    //查看
    toView:function(id){
      this.testAttachment = '';
      this.FileUpload = [];
      this.imageAttachment = '';
      this.FileUploadImg = [];
      this.videoAttachment = '';
      this.FileUploadVideo = [];
      let that = this;
      that.curId = 0;
      that.studentObj = {};
      that.$post(
        that.urls.getStudent,
        {"id": id}
      )
        .then(function(res) {
          if(res.success) {
            that.studentObj = res.data;
            that.testAttachment = res.data.testAttachment;
            that.imageAttachment = res.data.imageAttachment;
            that.videoAttachment = res.data.videoAttachment;

            let enclosureList = [];  // 查看tex

            let enclosures = res.data.testAttachment.split(";");
            if(enclosures.length > 0 && res.data.testAttachment ) {
              enclosures.forEach(function (e) {
                enclosureList.push({
                  "name": that.getFileName(that.getFileName(e)),
                  "url": e
                });
              })
            }
            that.FileUpload = enclosureList;

            let imgArr = [];
            // 查看img
            let enclosuresImg = res.data.imageAttachment.split(";");
            if(enclosuresImg.length > 0 && res.data.imageAttachment) {
              enclosuresImg.forEach(function (e) {
                imgArr.push({
                  "name": that.getFileName(that.getFileName(e)),
                  "url":  e
                });
              })
            }
            that.FileUploadImg = imgArr;

            let video = [];  // 查看video
            let enclosuresVideo = res.data.videoAttachment.split(";");
            if(enclosuresVideo.length > 0 && res.data.videoAttachment) {
              enclosuresVideo.forEach(function (e) {
                video.push({
                  "name": that.getFileName(that.getFileName(e)),
                  "url":   e
                });
              })
            }
            that.FileUploadVideo = video;
          }
        })
      this.Application = true;
    },
    // 提交
    subForm: function () {
      let that = this;
      let flg = that.validate.form();
      if(flg){
        let   dataObj = that.combinationFormObject(that.validate.currentForm);
        console.log(dataObj)
        dataObj.auditStatus = 1;
        let url;
        let msg;

        let userUrl;
        if(that.studentId){
          url = that.urls.editStudent;
          msg = '修改学生成功！';
          dataObj.id = that.studentId;
          userUrl = that.urls.editUser;
        }else {
          url = that.urls.addStudent;
          msg = '新增学生成功！';
          userUrl = that.urls.addUser;
        }
        let obj = {"identityCard": dataObj.identityCard  };
        let ob = { "userAccount":dataObj.identityCard  };

        if(that.studentId){
          obj.id = that.studentId;
        }
        if(that.userId){
          ob.id = that.userId;
        }
        that.$post(
          that.urls.queryStudentHeavy,
          obj
        )
          .then(function(res) {
            if(res.success && res.data) {
              layer.msg('身份证已存在，请重新输入份证!', {
                time: 3000, //3s后自动关闭
              });
            }
            else {

              that.$post(
                that.urls.queryHeavy,
                ob
              )
                .then(function(res) {
                  if(res.success) {
                    layer.msg('身份证已存在,请重新输入!', {
                      time: 3000, //3s后自动关闭
                    });
                  }else {
                    // 提交

                    let o = {};
                    o.email = dataObj.reserved2;
                    o.expertName = dataObj.name;
                    o.userAccount = dataObj.identityCard;
                    o.expertGender = dataObj.reserved;
                    o.phoneNumber = dataObj.phone;
                    o.position = dataObj.industry;
                    o.userPassword = dataObj.identityCard.substr(obj.identityCard.length -6,obj.identityCard.length );

                    if(that.userId){
                      o.id =  that.userId;
                    }

                    that.$post(
                      that.urls.findRole,
                      {"roleName": '学生'}
                    )
                      .then(function(res) {
                        if(res.success) {

                          o.roleId = res.data.id;
                          o.roleName = "测试"; // 必须传

                          that.$post( // 添加 用户
                            userUrl,
                            o
                          )
                            .then(function(res) {
                              if(res.success) {
                                dataObj.userId = res.data;
                                that.$post(   // 添加学生
                                  url,
                                  dataObj
                                )
                                  .then(function(res) {

                                    if(res.success) {
                                      that.ApplicationStatus = false;
                                      //  that.closeModel();
                                      layer.msg(msg, {
                                        time: 3000, //3s后自动关闭
                                      });

                                      that.testAttachment = '';
                                      that.FileUpload = [];

                                      that.getStudent();
                                    }else {
                                      layer.msg('失败！', {
                                        time: 3000, //3s后自动关闭
                                      });
                                    }

                                  })

                              }
                            })
                        }
                      })

                  }

                })


            }
          })

      }
    },
    // add user
    addUser: function (obj){
      let that = this;
       let o = {};
     o.expertName = obj.name;
      o.userAccount = obj.identityCard;
      o.expertGender = obj.reserved ;
      o.phoneNumber = obj.phone;
      o.position = obj.industry;
      o.userPassword = obj.identityCard.substr(obj.identityCard.length -6,obj.identityCard.length );

      that.$post(
        that.urls.findRole,
        {"roleName": '学生'}
      )
        .then(function(res) {
          if(res.success) {

            o.roleId = res.data.id;
            o.roleName = "测试"; // 必须传

            that.$post(
              that.urls.addUser,
              o
            )
              .then(function(res) {
                if(res.success) {

                }
              })
          }
        })




    },



    //关闭模态框
    closeModel: function() {
      this.Application = false;
      this.ApplicationStatus = false;
      this.testAttachment = '';
      this.FileUpload = [];
      this.imageAttachment = '';
      this.FileUploadImg = [];
      this.videoAttachment = '';
      this.FileUploadVideo = [];
    },

    touchOffIdInput(n) {
      this.uploadNum = n;
      if(n == 1) {
        $("#imageAttachment").click();
      }
    },
    /**文件上传(多文件)js  文本附件 **/
    idFrontImg: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              that.FileUpload.push( {"name": that.getFileName(fileInfos[i].url), "url": fileInfos[i].url  }  );
            }
            console.log(urls)
            if(that.testAttachment.length > 0){
              that.testAttachment += ";" + urls.join(";");
            }else {
              that.testAttachment = urls.join(";");
            }

          }
        })
    }, // 点击

    touchImg(n) {
      this.uploadNum = n;
      if(n == 1) {
        $("#touchImg").click();
      }
    }, // 图片

    touchUploadImg: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              that.FileUploadImg.push( {"name": that.getFileName(fileInfos[i].url), "url": fileInfos[i].url  }  );
            }
            console.log(urls)
            if(that.imageAttachment.length > 0){
              that.imageAttachment += ";" + urls.join(";");
            }else {
              that.imageAttachment = urls.join(";");
            }

          }
        })
    }, // 图片


    touchVideo(n) {
      this.uploadNum = n;
      if(n == 1) {
        $("#touchVideo").click();
      }
    }, // 视频

    idFrontVideo: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              that.FileUploadVideo.push( {"name": that.getFileName(fileInfos[i].url), "url": fileInfos[i].url  }  );
            }
            console.log(urls)
            if(that.videoAttachment.length > 0){
              that.videoAttachment += ";" + urls.join(";");
            }else {
              that.videoAttachment = urls.join(";");
            }

          }
        })
    }, // 视频

    /*  		let enclosures = enclosure.split(";"); */
    //下载资源
    downloadResources: function(filePath) {
      if(filePath != null && filePath != "") {
        window.location.href = this.urls.download + "?path=" + filePath;
      }else {
        layer.msg('暂无附件', {
          time: 3000, //3s后自动关闭
        });
      }
    },

    // 跳转到预览
    toSrc: function (url) {
      console.log(url)
      if(url == null || url == undefined || url == ''){
        layer.msg('暂无附件', {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      window.open(this.thatUrl + url);
    },

    // 点击切换按钮
    clickcurId: function (id) {
      this.curId = id;
      console.log( this.curId)
    },

    //删除附件
    del: function (f) {
      let that = this;


      layer.confirm('你确定要删除吗?', {icon: 3, title:'提示'}, function(index){

        if(that.curId == 0){
          if(that.FileUpload.length > 0){
            let arr = [];
            let urls = [];
            that.FileUpload.forEach(function (e) {
              if(f.name != e.name){
                urls.push(e.url);
                arr.push(e);
              }
            })
            that.FileUpload = arr;
            that.testAttachment = urls.join(";");
          }
        }else if(that.curId == 1){
          if(that.FileUploadImg.length > 0){
            let arr = [];
            let urls = [];
            that.FileUploadImg.forEach(function (e) {
              if(f.name != e.name){
                urls.push(e.url);
                arr.push(e);
              }
            })
            that.FileUploadImg = arr;
            that.imageAttachment = urls.join(";");
          }
        }else if(that.curId == 2){
          if(that.FileUploadVideo.length > 0){
            let arr = [];
            let urls = [];
            that.FileUploadVideo.forEach(function (e) {
              if(f.name != e.name){
                urls.push(e.url);
                arr.push(e);
              }
            })
            that.FileUploadVideo = arr;
            that.videoAttachment = urls.join(";");
          }
        }

      });

    },
    subStrThe: function (str) {
      if(str) {
        if (str.length > 10) {
          let s = str.substr(0, 9);
          return s + '...';
        } else {
          return str;
        }
      }
    },// 导出
    exportStudent : function () {
      window.location.href = this.urls.exportStudent + "?"  + $('#searchName').val() + "=" + this.searchValue;
    },


    //导入数据
    inputData: function (event) {
      let that = this;
      var file = event.currentTarget.files[0];
      if (!that.fileGlobalFilter(file)) {
        return;
      }
      let formData = new FormData();
      formData.append('fileNames', file);
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.studentImportExcel,
        formData,
        config
      )
        .then(function(res) {
          let msg = '';
          if(res.success) {
            msg = "导入成功！";
            that.getStudent();
          } else {
            msg = "导入失败！";
          }
          layer.msg(msg, {
            time: 3000, //3s后自动关闭
          });
        })
    }
  }
}
